<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class WeChatSupportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'support:vod';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'update vod class namespace.';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'support vod';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->namespaceUpdate();
        $this->reImportClass();
        $this->info($this->type . ' created successfully.');
    }

    private function namespaceUpdate()
    {
        $classes = [
            ["classPath" => 'Http\Controllers\Api\VodController.php', 'namespace' => 'App\Http\Controllers\Api'],
            ["classPath" => 'Validators/VodValidator.php', 'namespace' => 'App\Validators'],
        ];
        foreach ($classes as $item) {
            $path = app_path($item['classPath']);
            if (!file_exists($path)) {
                $this->info("namespace update fail: file[$path] not exist.");
                return;
            }
            $content = File::get($path);
            File::put($path, preg_replace("/namespace.*/", "namespace " . $item['namespace'] . ";", $content));
        }
    }

    private function reImportClass()
    {
        $classes = [
            ["classPath" => 'Http\Controllers\Api\VodController.php', 'reImportClasses' => [
                ['old' => 'Ktnw\VodSupport\Validators\VodValidator', 'new' => 'App\Validators\VodValidator'],
            ]],
        ];
        foreach ($classes as $item) {
            $path = app_path($item['classPath']);
            if (!file_exists($path)) {
                $this->info("reImport class update fail: file[$path] not exist.");
                return;
            }
            $reImportClasses = $item["reImportClasses"];
            if (!empty($reImportClasses)) {
                $content = File::get($path);
                foreach ($reImportClasses as $importClass) {
                    $content = str_replace($importClass["old"], $importClass["new"], $content);
                }
                File::put($path, $content);
            }
        }
    }


}
